package com.tanhua.server.controller;


import com.tanhua.domain.db.User;
import com.tanhua.server.interceptor.UserThreadLocal;

import com.tanhua.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("users")
public class UsersController {

    @Autowired
    private UserService userService;

    /**
     * 上传头像
     */
    @RequestMapping("header")
    @PostMapping
    public ResponseEntity<Object> saveLogo(@RequestParam("headPhoto") MultipartFile file, @RequestHeader("Authorization") String token) throws IOException {
        User user = UserThreadLocal.get();
        return this.userService.saveLogo(file, user);
    }

    /**
     * 发送验证码
     */
    @PostMapping("phone/sendVerificationCode")
    public ResponseEntity<Object> sendVerificationCode() {
        User user = UserThreadLocal.get();
        String phone = user.getMobile();
        return userService.sendCheckCode(phone);
    }


    /**
     * 校验验证码
     */
    @PostMapping("phone/checkVerificationCode")
    public ResponseEntity<Map<String, Object>> checkVerificationCode(@RequestBody Map<String, String> param) {
        String code = param.get("verificationCode");
        boolean bool = userService.checkCode(UserThreadLocal.getUserMobile(),code);
        Map<String, Object> result = new HashMap<>();
        result.put("verification", bool);
        return ResponseEntity.ok(result);
    }

    /**
     * 保存新的手机号
     */
    @PostMapping("phone")
    public ResponseEntity<Void> saveNewMobile(@RequestBody Map<String, String> param, @RequestHeader("Authorization") String token){
        User user = UserThreadLocal.get();
        String newPhone = param.get("phone");
        user.setMobile(newPhone);
        return userService.saveNewMobile(user);
    }
}
